import { createRouter, createWebHistory } from 'vue-router'
import Login from '../views/Login.vue'
import Home from '../views/Home.vue'
import NewsList from '../views/news/newsList/index.vue';

const routes = [
  {
    path: '/login',
    name: 'Login',
    component: Login,
    meta: { requiresAuth: false }
  },
  {
    path: '/',
    name: 'Home',
    component: Home,
    meta: { requiresAuth: true },
    children: [
      {
        path: 'comments',
        name: 'CommentManage',
        component: () => import('../views/CommentManage.vue'),
        meta: {
          requiresAuth: true,
          title: '评论管理'
        }
      },
      {
        path: '/apinews/list',
        name: 'NewsList',
        component: NewsList
      },
      {
        path: '/apinews/add',
        name: 'NewsAdd',
        component: () => import('../views/news/newsAdd/index.vue')
      },
      {
        path: '/apinews/edit/:id',
        name: 'NewsEdit',
        component: () => import('../views/news/newsEdit/index.vue')
      },
      {
        path: '/apiusers/list',
        name: 'UserList',
        component: () => import('../views/users/userList/index.vue')
      },
      {
        path: '/apiusers/add',
        name: 'UserAdd',
        component: () => import('../views/users/userAdd/index.vue')
      },
      {
        path: '/apiusers/edit/:id',
        name: 'UserEdit',
        component: () => import('../views/users/userEdit/index.vue')
      }
    ],
    


  }
]

const router = createRouter({
  history: createWebHistory(),
  routes
})

// 路由守卫
router.beforeEach((to, from, next) => {
  const token = localStorage.getItem('token')

  if (to.meta.requiresAuth && !token) {
    // 需要登录但未登录，重定向到登录页
    next('/login')
  } else if (to.path === '/login' && token) {
    // 已登录但访问登录页，重定向到首页
    next('/')
  } else {
    // 设置页面标题
    document.title = to.meta.title || '后台管理系统'
    next()
  }
})

export default router
